import { defineComponent } from 'vue';
import { NButton } from 'naive-ui';
import modeler from '@wf/components/bpmnjs/store/modeler';
import BpmnModdle from 'bpmn-moddle';
import { useI18n } from 'vue-i18n';

const SaveFlow = defineComponent({
  name: 'SaveFlow',
  emits: ['saveFlow', 'saveJson'],
  setup(props, { emit }) {
    const { t } = useI18n();
    const modelerStore = modeler();
    const moddle = new BpmnModdle();

    const saveXML = async () => {
      const modeler = modelerStore.getModeler!;
      const { xml } = await modeler.saveXML({ format: true });
      const jsonStr = await moddle.fromXML(xml!);
      const json = JSON.stringify(jsonStr, null, 2)
      emit('saveFlow', xml);
      emit('saveJson', json);
      console.log('saveXml', xml);
      console.log('saveJson', json);
    };

    return () => (
      <span>
        <NButton type="info" secondary onClick={saveXML}>
          {t('toolbar.saveFile')}
        </NButton>
      </span>
    );
  }
});

export default SaveFlow;
